package com.hxzy.controller.admin;

import com.hxzy.common.controller.BaseController;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import com.hxzy.dto.ProductDTO;
import com.hxzy.dto.ProductSearch;
import com.hxzy.service.MerchandiseService;
import com.hxzy.util.SSMThreadLocal;
import com.hxzy.vo.AdminLoginVO;
import com.hxzy.vo.ProductVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 商品信息API
 *
 * @author tonneyyy
 */
@Api(tags = "商品信息API")
@RestController
@RequestMapping(value = "/api/product")
public class ProductController extends BaseController {

    /**
     * 商品信息业务逻辑
     */
    @Autowired
    private MerchandiseService merchandiseService;


    @ApiOperation(value = "商品分页查询")
    @GetMapping(value = "/data")
    public R search(ProductSearch productSearch){
        super.buildPage(productSearch);

        AdminLoginVO adminLoginVO= SSMThreadLocal.adminLoginVOThreadLocal.get();
        //商家只允许查询自己的信息
        if(adminLoginVO.getType()==1){
            productSearch.setBid(adminLoginVO.getId());
        }


        List<ProductVO> list=this.merchandiseService.search(productSearch);
        return super.pageToPageVO(list);
    }

    @ApiOperation(value = "根据主键查询")
    @GetMapping(value = "/{id}")
    public R findById(@PathVariable(value = "id") Long id){
       ProductVO  productVO= this.merchandiseService.findById(id);
       if(productVO==null){
           return R.build(AckCode.NOT_FOUND_DATA);
       }
        return R.okHasData(productVO);
    }

    @ApiOperation(value = "新增保存")
    @PostMapping
    public R add(@RequestBody @Valid ProductDTO  productDTO){

       int count= this.merchandiseService.add(productDTO);
       return super.toR(count);
    }

    @ApiOperation(value = "修改保存")
    @PutMapping
    public R update(@RequestBody @Valid ProductDTO  productDTO){
        int count= this.merchandiseService.update(productDTO);
        return super.toR(count);
    }
}
